package com.pda.xinma.ui.handingin;

import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.pda.xinma.R;
import com.pda.xinma.bean.HandingInDetailBean;
import com.pda.xinma.bean.ScanBean;
import com.pda.xinma.bean.ScanResultBean;
import com.pda.xinma.bean.request.HandingInRequest;
import com.pda.xinma.bean.request.QRcodeRequest;
import com.pda.xinma.contract.HandingInContract;
import com.pda.xinma.dialog.AffirmDialog;
import com.pda.xinma.net.NetUtils;
import com.pda.xinma.presenter.HandingInPresenter;
import com.pda.xinma.view.ScanButView;
import com.wangshen.base.config.StringKey;
import com.wangshen.base.net.bean.BaseAppEntity;
import com.wangshen.base.ui.mvp.base.ui.BaseMvpFragment;
import com.wangshen.base.util.SharedPreferencesUtil;
import com.wangshen.base.util.ToastUtils;

import org.greenrobot.eventbus.EventBus;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

public class HandingInFragment extends BaseMvpFragment<HandingInPresenter> implements HandingInContract.View {
    @BindView(R.id.tv_deliveryNo)
    TextView tvDeliveryNo;

    @BindView(R.id.sb_scan)
    ScanButView sbScan;
    @BindView(R.id.tv_move_out)
    TextView tvMoveOut;
    @BindView(R.id.tv_storageBin)
    TextView tvStorageBin;
    @BindView(R.id.tv_productModel)
    TextView tvProductModel;
    @BindView(R.id.ll7)
    LinearLayout ll7;
    @BindView(R.id.tv_batch)
    TextView tvBatch;
    @BindView(R.id.ll8)
    LinearLayout ll8;
    @BindView(R.id.tv_indexNo)
    TextView tvIndexNo;
    @BindView(R.id.tv_weight)
    EditText tvWeight;
    @BindView(R.id.tv_actualWeight)
    TextView tvActualWeight;
    @BindView(R.id.tv_apparentDensity)
    TextView tvApparentDensity;
    @BindView(R.id.tv_liquidity)
    TextView tvLiquidity;
    @BindView(R.id.tv_produceDate)
    TextView tvProduceDate;
    @BindView(R.id.tv_shelfLifeDate)
    TextView tvShelfLifeDate;
    @BindView(R.id.tv_container)
    TextView tvContainer;
    @BindView(R.id.ll_wight)
    LinearLayout llWight;
    @BindView(R.id.tv_thirdOrderNo)
    TextView tvThirdOrderNo;
    private String storageBin;
    private boolean isScan = false;

    public HandingInFragment(String entryNo) {
        this.entryNo = entryNo;
    }

    public HandingInFragment(HandingInDetailBean handingInDetailBean) {
        this.handingInDetailBean = handingInDetailBean;
    }

    public HandingInFragment() {
    }

    private String entryNo;

    @Override
    public HandingInPresenter getPresenter() {
        return new HandingInPresenter();
    }

    @Override
    public int getViewId() {
        return R.layout.fragment_handing_in;
    }

    @Override
    public void initView() {
        if (handingInDetailBean != null) {
            isScan = true;
            tvThirdOrderNo.setText("第三方单号："+handingInDetailBean.getThirdOrderNo());
            presenter.queryEntryScanShelvesInfo(handingInDetailBean.getThirdOrderNo(),handingInDetailBean);
            //setData(handingInDetailBean);
        } else {
            isScan = false;
            tvDeliveryNo.setText("入库单信息 " + entryNo);
            presenter.queryEntryShelvesInfo(entryNo, storageBin);
        }
        storageBin = SharedPreferencesUtil.getInstance().getString(StringKey.STORAGEBIN, "");
        if (!TextUtils.isEmpty(storageBin)) {
            tvStorageBin.setText(storageBin);
            presenter.queryActualWeight(storageBin);
        }
    }

    public void getCode(QRcodeRequest request) {
        NetUtils.geApi().scanTheQRCodeToVerify(request)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<BaseAppEntity<ScanResultBean>>() {
                    @Override
                    public void accept(BaseAppEntity<ScanResultBean> stringBaseAppEntity) throws Exception {
                        if (!stringBaseAppEntity.getCode().equals("200")) {
                            ToastUtils.showToast(getContext(), stringBaseAppEntity.getMessage());
                            return;
                        }
                        if (stringBaseAppEntity.getData().getType().equals("B")) {
                            storageBin = stringBaseAppEntity.getData().getCode();
                            //SharedPreferencesUtil.getInstance().putString(StringKey.STORAGEBIN, storageBin);
                            tvStorageBin.setText(stringBaseAppEntity.getData().getCode());
                            presenter.queryActualWeight(storageBin);
                            //presenter.queryEntryShelvesInfo(entryNo, storageBin);
                        } else if (stringBaseAppEntity.getData().getType().equals("A")) {
                            time = 0;
                            tvContainer.setText(stringBaseAppEntity.getData().getCode());
                            presenter.queryActualWeight(storageBin);
                            //presenter.queryEntryShelvesInfo(entryNo, storageBin);
                            //presenter.queryEntryShelvesInfo(entryNo, stringBaseAppEntity.getData().getCode());
                        } else {
                            ToastUtils.showToast(getContext(), "请扫正确的条形码");
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        ToastUtils.showToast(getContext(), throwable.getMessage());
                    }
                });
    }

    @Override
    public void initLinsenterner() {

    }

    @Override
    public void onResume() {
        super.onResume();
        sbScan.setScanCallBack(new ScanButView.ScanCallBack() {
            @Override
            public void callBack(ScanBean scanBean) {
                if (scanBean.getCode().contains(",")) {
                    String[] parts = scanBean.getCode().split(",");
                    HandingInDetailBean handingInDetailBean = new HandingInDetailBean();
                    try {
                        handingInDetailBean.setThirdOrderNo(parts[0]);
                        handingInDetailBean.setBatch(parts[1]);
                        handingInDetailBean.setProductModel(parts[2]);
                        handingInDetailBean.setIndexNo(parts[3]);
                        handingInDetailBean.setWeight(parts[4]);
                        handingInDetailBean.setApparentDensity(parts[5]);
                        handingInDetailBean.setLiquidity(parts[6]);
                        handingInDetailBean.setProduceDate(parts[7]);
                        handingInDetailBean.setShelfLifeDate(parts[8]);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    if (isScan) {
                        presenter.queryEntryScanShelvesInfo(handingInDetailBean.getThirdOrderNo(),handingInDetailBean);
                    } else {
                        setData(handingInDetailBean);
                    }

                } else {
                    QRcodeRequest request = new QRcodeRequest();
                    request.setQRCode(scanBean.getCode());
                    request.setQRCodeType("1");
                    getCode(request);
                }

            }
        });
    }

    @Override
    public void onPause() {
        super.onPause();
        sbScan.setScanCallBack(null);
    }

    @Override
    public void getData() {

    }


    HandingInDetailBean handingInDetailBean;

    @Override
    public void setData(HandingInDetailBean data) {
        if (isScan) {
            this.handingInDetailBean = data;
            tvThirdOrderNo.setText("第三方单号："+handingInDetailBean.getThirdOrderNo());
            tvApparentDensity.setText(data.getApparentDensity());
            tvBatch.setText(data.getBatch());
            tvIndexNo.setText(data.getIndexNo() + "");
            tvLiquidity.setText(data.getLiquidity());
            tvProduceDate.setText(data.getProduceDate());
            tvShelfLifeDate.setText(data.getShelfLifeDate());
            tvProductModel.setText(data.getProductModel());
            tvWeight.setText(data.getWeight() + "");
            tvIndexNo.setText(data.getIndexNo());
        } else {
            if (handingInDetailBean != null){
                if (data.getThirdOrderNo().equals(handingInDetailBean.getThirdOrderNo())){
                    //this.handingInDetailBean = data;
                    tvApparentDensity.setText(data.getApparentDensity());
                    tvBatch.setText(data.getBatch());
                    tvIndexNo.setText(data.getIndexNo() + "");
                    tvLiquidity.setText(data.getLiquidity());
                    tvProduceDate.setText(data.getProduceDate());
                    tvShelfLifeDate.setText(data.getShelfLifeDate());
                    tvProductModel.setText(data.getProductModel());
                    tvWeight.setText(data.getWeight() + "");
                    tvIndexNo.setText(data.getIndexNo());
                    tvThirdOrderNo.setText("第三方单号："+data.getThirdOrderNo());
                }else {
                    showMessage("单号不一致，请核对！");
                    finishActivity();
                }
            }else {
                this.handingInDetailBean = data;
                tvApparentDensity.setText(data.getApparentDensity());
                tvBatch.setText(data.getBatch());
                tvIndexNo.setText(data.getIndexNo() + "");
                tvLiquidity.setText(data.getLiquidity());
                tvProduceDate.setText(data.getProduceDate());
                tvShelfLifeDate.setText(data.getShelfLifeDate());
                tvProductModel.setText(data.getProductModel());
                tvWeight.setText(data.getWeight() + "");
                tvIndexNo.setText(data.getIndexNo());
            }
          /*  if (data.getThirdOrderNo().equals(handingInDetailBean.getThirdOrderNo())) {*/

            /*} else {

            }*/
        }


        //tvProductTime.setText(data.getP);
    }

    @Override
    public void setScanData(HandingInDetailBean data) {
        entryNo = data.getEntryNo();
        tvDeliveryNo.setText("入库单信息 " + entryNo);
        EventBus.getDefault().post(entryNo);
        this.handingInDetailBean = data;
        setData(data);
    }

    @Override
    public void setWeight(String weight) {
        tvActualWeight.setText(weight);
    }

    @Override
    public void onSuccess() {
        tvContainer.setText("");
        tvActualWeight.setText("");
        tvApparentDensity.setText("");
        tvBatch.setText("");
        tvIndexNo.setText("");
        tvLiquidity.setText("");
        tvProduceDate.setText("");
        tvShelfLifeDate.setText("");
        tvProductModel.setText("");
        tvActualWeight.setText("");
        tvWeight.setText("");
        tvIndexNo.setText("");
        llWight.requestFocus();
        time = 0;
        if (!TextUtils.isEmpty(storageBin)) {
            presenter.queryEntryShelvesInfo(entryNo, storageBin);
        }
    }

    private long time = 0;

    @OnClick({R.id.sb_scan, R.id.tv_move_out})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.sb_scan:
                break;
            case R.id.tv_move_out:
                if (time == 0) {
                    time = System.currentTimeMillis();
                } else {
                    if (System.currentTimeMillis() - time < 10000) {
                        time = System.currentTimeMillis();
                        showMessage("请不要重复提交！");
                        return;
                    }
                }
                if (TextUtils.isEmpty(tvStorageBin.getText())) {
                    showMessage("作业库位不能为空！");
                    return;
                }
                if (TextUtils.isEmpty(entryNo)){
                    showMessage("单号不能为空！");
                    return;
                }
                HandingInRequest request = new HandingInRequest();
                request.setEntryNo(entryNo);
                request.setRollerId(storageBin);
                request.setSku(handingInDetailBean.getSku());
                request.setNumId(handingInDetailBean.getNumId());
                request.setIndexNo(tvIndexNo.getText().toString());
                request.setApparentDensity(handingInDetailBean.getApparentDensity());
                request.setLiquidity(handingInDetailBean.getLiquidity());
                request.setActualWeight(tvActualWeight.getText().toString());
                request.setProduceDate(handingInDetailBean.getProduceDate());
                request.setShelfLifeDate(handingInDetailBean.getShelfLifeDate());
                try {
                    request.setWeight(tvWeight.getText().toString());
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                    showMessage("请输入数字");
                    return;
                }
                request.setContainer(tvContainer.getText().toString());
                AffirmDialog dialog = new AffirmDialog(mContext, new AffirmDialog.OnConfrim() {
                    @Override
                    public void onConfrim() {
                        presenter.confirmIssued(request);
                    }
                });
                dialog.show("确认要上架吗？");
                break;
        }
    }
}
